import { ref } from 'vue'
import { onActivated } from 'vue'
import { useRoute } from 'vue-router'

export function useRecoverElScrollbarPosition(elScrollbarInstance) {
  const $route = useRoute()
  const _systemBasePageScrollTopRef = ref()
  const _systemBasePageScrollLeftRef = ref()

  function onScroll({ scrollTop, scrollLeft }) {
    if ($route.meta.keepAlive) {
      _systemBasePageScrollTopRef.value = scrollTop
      _systemBasePageScrollLeftRef.value = scrollLeft
    }
  }

  onActivated(() => {
    if ($route.meta.keepAlive) {
      if (_systemBasePageScrollTopRef.value) {
        elScrollbarInstance.value.setScrollTop(
          _systemBasePageScrollTopRef.value
        )
      }
      if (_systemBasePageScrollLeftRef.value) {
        elScrollbarInstance.value.setScrollLeft(
          _systemBasePageScrollLeftRef.value
        )
      }
    }
  })

  return { onScroll }
}
